#!/usr/bin/python
# -*- coding: UTF-8 -*-

from lib.base import Douyin
from sms.sms import Sms
from random import randint
import random, logging, sys, re, os
from faker import Faker

from exception.error import ImageYanzhengmaRuntimeError
from exception.error import PhoneCodeTimeoutRuntimeError
from exception.error import PhoneCodeWrongRuntimeError
from exception.error import PhoneBannedRuntimeError


class Register(Douyin):
    def __init__(self, sn):
        super(Register, self).__init__(sn)
        fd = open("{0}/../log/register/{1}.log".format(os.path.dirname(__file__), sn), "w")
        sys.stdout = sys.stderr = fd
        self.sms = Sms()
        self.faker_obj = Faker(locale='zh_CN')

    def write_name(self):
        logging.warning("进入填写资料页面")

        logging.warning("填写姓名")
        self.device(resourceId="com.ss.android.ugc.aweme:id/nw").click_exists(timeout=3)
        self.write_text(self.faker_obj.name())

    def choose_birth(self):
        self.sleep(1)
        self.device(text="点击设置出生日期").click_exists(timeout=1)
        self.device(resourceId="com.ss.android.ugc.aweme:id/nx").click_exists(timeout=1)

        bounds = self.device(resourceId="com.ss.android.ugc.aweme:id/a5u").info['bounds']
        middle = (bounds['left'] + bounds['right'])/2
        middle_height = (bounds['bottom'] + bounds['top'])/2
        for i in range(randint(1, 4)):
            self.swipe(middle, bounds['top'], middle, middle_height, 0.1)    

        bounds = self.device(resourceId="com.ss.android.ugc.aweme:id/a5v").info['bounds']
        middle = (bounds['left'] + bounds['right'])/2
        middle_height = (bounds['bottom'] + bounds['top'])/2
        for i in range(randint(1, 4)):
            self.swipe(middle, bounds['top'], middle, middle_height, 0.1)    

        bounds = self.device(resourceId="com.ss.android.ugc.aweme:id/a5w").info['bounds']
        middle = (bounds['left'] + bounds['right'])/2
        middle_height = (bounds['bottom'] + bounds['top'])/2
        for i in range(randint(2, 23)):
            self.swipe(middle, bounds['top'], middle, middle_height, 0.2) 

        self.click(300, 300) 

    def submit_phone_and_code(self):
        if self.current_app()['activity'] != "com.ss.android.ugc.aweme.account.login.ui.LoginOrRegisterActivity":
            logging.warning("不在注册页面退出")
            self.run(name)

        resp = self.device(text="输入手机号码").click_exists(timeout=2)
        self.reportClick(resp, '未找到输入手机号码的地方')

        phone = ""
        while True:
            logging.warning("正在获取手机号码...")
            phone = self.sms.get_phone()
            if phone is not None:
                if phone is not False:
                    logging.warning("收到手机号:{}".format(phone))
                    break
            self.sleep(1)

        logging.warning("输入手机号")
        self.write_text(phone)
        self.sleep(2)
        self.device(text="获取验证码").click()

        if self.check_is_image_verify():
            logging.warning("检测到拼图或相似图形验证码")
            raise ImageYanzhengmaRuntimeError("")

        self.sleep(10)
        logging.warning("开始请求手机号")
        code = self.sms.get_sms(phone)
        # 检测验证码是否为 None
        if code is None:
            logging.warning("验证码获取失败，释放号码： %s" % phone)
            if self.sms.release_phone(phone):
                logging.warning("已经释放号码")
            raise(PhoneCodeTimeoutRuntimeError(""))

        logging.warning("输入验证码")
        self.device(text="输入短信验证码").click()
        self.write_text(code)
        #self.press_back()
        self.sleep(2)

        logging.warning("点击注册按钮")
        self.device(resourceId="com.ss.android.ugc.aweme:id/cmc").click_exists(timeout=3)
        self.device(resourceId="com.ss.android.ugc.aweme:id/l1").click_exists(timeout=3)

        return phone

    def submit_then_check(self, phone):
        logging.warning("判断是否还在该页面，因为可能验证码不对")
        self.sleep(10)
        if self.device(text="密码登录").exists(timeout=5):
            self.sms.block_phone(phone)
            logging.warning("验证码不对")
            raise PhoneCodeWrongRuntimeError("")

        logging.warning("检测是否封禁弹窗")
        if self.device(text="取消").click_exists(timeout=5):
            self.sms.block_phone(phone)
            logging.warning("手机被封禁")
            raise PhoneBannedRuntimeError("")

        if not self.device(text="完善资料"):
            logging.warning("未进入填写资料页面")
            raise RuntimeError("xx")

    def choose_sex(self):
        self.device(text="点击设置性别").click_exists(timeout=2)
        self.device(resourceId="com.ss.android.ugc.aweme:id/ny").click_exists(timeout=1)
        self.sleep(1)
        bounds = self.device(resourceId="com.ss.android.ugc.aweme:id/a7i").info['bounds']
        middle = (bounds['left'] + bounds['right'])/2
        middle_height = (bounds['bottom'] + bounds['top'])/2
        self.swipe(middle, middle_height, middle, bounds['top']+10, 0.3)   
        self.press_back()

    def submit_info(self):
        if not self.device(resourceId="com.ss.android.ugc.aweme:id/nz").click_exists(timeout=2):
            logging.warning("没有找到资料提交按钮")
        self.sleep(2)
        if self.check_is_image_verify():
            logging.warning("出验证码了")
            raise ImageYanzhengmaRuntimeError("")

    def start(self):
        for i in range(1, 21):
            try:
                self.run("{}".format(i))
            except Exception as e:
                logging.warning(str(e))

    def run(self, name):
        if not self.open_douyin(int(name)):
            logging.warning("没有打开{}号app".format(name))
            return
        self.handle()

    def run_once_by_pname(self, p_name):
        self.open_douyin_by_packname(p_name)
        self.handle()

    def handle(self):
        self.sleep(8)
        self.click_city()

        for i in range(3):
            self.check_window()

        if not self.check_is_not_login():
            logging.warning("已经登录")
            return

        logging.warning("未登录,开始注册")
        phone = self.submit_phone_and_code()

        logging.warning("注册完检查")
        self.submit_then_check(phone)

        logging.warning("填写姓名")
        self.write_name()

        #logging.warning("选择生日")
        #self.choose_birth()

        logging.warning("选择性别")
        self.choose_sex()

        logging.warning("提交信息页")
        self.submit_info()

        self.sleep(2)

        self.device(text="消息").click_exists(timeout=3)




        








        
